/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.huawei.housekeeper.constants.DeletedFlagEnum;
import com.huawei.housekeeper.constants.RabbitMqTopicConfig;
import com.huawei.housekeeper.constants.TaskOrderAction;
import com.huawei.housekeeper.dao.entity.Task;
import com.huawei.housekeeper.dao.mapper.TaskMapper;
import com.huawei.housekeeper.entity.MessageServiceEntity;
import com.huawei.housekeeper.entity.OrderMessageEntity;
import com.huawei.housekeeper.enums.ErrorCode;
import com.huawei.housekeeper.exception.Assert;
import com.huawei.housekeeper.feign.UserInfoService;
import com.huawei.housekeeper.feign.request.PageQueryAllUserDto;
import com.huawei.housekeeper.feign.response.GetTenantUserInfoVo;
import com.huawei.housekeeper.utils.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
/**
 * 功能描述 接受来自订单服务发送来的消息，生成相应的任务
 *
 * @since 2022-03-03
 */
@Log4j2
@Service
public class RabbitMqOrderServiceImpl {
    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private MessageServiceUtil messageServiceUtil;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 接受来自订单服务发送来的消息，生成相应的任务
     *
     * @param message
     * @throws JsonProcessingException 消息转换异常
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
    @RabbitListener(queues = {RabbitMqTopicConfig.QUEUE_TASK})
    public void receiveOrderMsgFromMsgService(String message) throws JsonProcessingException {
        Assert.notNull(message, ErrorCode.TENANT_MISS_ERROR.getCode(), ErrorCode.MESSAGE_ERROR.getMessage());

        OrderMessageEntity orderMessageEntity = JsonUtil.jsonToPojo(message, OrderMessageEntity.class);
        TaskOrderAction taskOrderAction = TaskOrderAction.ofAction(orderMessageEntity.getTaskOrderAction())
                .orElseGet(() -> TaskOrderAction.TASK_ORDER_WAITING);
        LambdaQueryWrapper<Task> selectQuery = Wrappers.lambdaQuery();
        selectQuery.eq(Task::getOrderId, orderMessageEntity.getOrderId());
        Task oldTask = taskMapper.selectOne(selectQuery);
        log.info("--receiveOrderMsgFromMsgService->task.orderId={},taskOrderAction: {}",
                orderMessageEntity.getOrderId(), taskOrderAction.getAction());
        if (taskOrderAction == TaskOrderAction.TASK_ORDER_WAITING) {
            Task taskEntity = buildTask(orderMessageEntity);
            boolean isSuccess = false;
            if (oldTask == null) {
                taskMapper.insert(taskEntity);
                isSuccess = true;
            }
            sendMsgToMsgService(orderMessageEntity, taskOrderAction, isSuccess);
        } else {
            Assert.notNull(oldTask, ErrorCode.TASK_NOT_EXIST.getCode(), ErrorCode.TASK_NOT_EXIST.getMessage());
            oldTask.setTaskStatus(taskOrderAction.getAction());
            taskMapper.updateById(oldTask);
            sendMsgToMsgService(orderMessageEntity, taskOrderAction, true);
        }

    }

    /**
     * 订单创建成功后发送消息
     *
     * @param orderMessageEntity
     * @throwsJsonProcessingException
     */
    private void sendMsgToMsgService(OrderMessageEntity orderMessageEntity, TaskOrderAction taskOrderAction, boolean isSuccess) throws JsonProcessingException {
        String msgTempage = "";
        String title = "";
        if (taskOrderAction == TaskOrderAction.TASK_ORDER_WAITING) {
            title = "任务大厅：来自{0}的订单消息";
            if (isSuccess) {
                msgTempage = "附近有{0}服务的派单，请留意!";
            } else {
                msgTempage = "{0}服务的订单任务已存在!";
            }
            title = MessageFormat.format(title, orderMessageEntity.getCustomerName());
            msgTempage = MessageFormat.format(msgTempage, orderMessageEntity.getServiceName());
        } else {
            msgTempage = "{0}服务{1}!";
            title = "任务大厅：{0}的订单状态已变更";
            title = MessageFormat.format(title, orderMessageEntity.getCustomerName());
            msgTempage = MessageFormat.format(msgTempage, orderMessageEntity.getServiceName(),
                    taskOrderAction.getMessage());
        }
        PageQueryAllUserDto pageQueryAllUserDto = new PageQueryAllUserDto();
        pageQueryAllUserDto.setAccountType(2);
        pageQueryAllUserDto.setCurrent(1);
        pageQueryAllUserDto.setSize(10);
        List<GetTenantUserInfoVo> result = userInfoService.getAllUserInfoList(pageQueryAllUserDto).getRecords();
        String finalTitle = title;
        String finalMsgTempage = msgTempage;
        Assert.isTrue(ObjectUtils.isNotEmpty(result), ErrorCode.QUERY_RESULT_EMPTY.getCode(), ErrorCode.QUERY_RESULT_EMPTY.getMessage());
        result.forEach(e -> {
            MessageServiceEntity messageServiceEntity = new MessageServiceEntity();
            messageServiceEntity.setUserId(e.getUserId());
            messageServiceEntity.setTime(new Date());
            messageServiceEntity.setTitle(finalTitle);
            messageServiceEntity.setMsg(finalMsgTempage);
            try {
                messageServiceUtil.sendMsgToMsgService(RabbitMqTopicConfig.MESSAGE_TASK_ORDER, messageServiceEntity);
            } catch (JsonProcessingException jsonProcessingException) {
                log.error("--->Json处理异常: ", jsonProcessingException);
            }
        });
    }

    /**
     * 根据mq消息初始化任务实体
     *
     * @param orderMessageEntity
     * @return {@link Task}
     * @throws JsonProcessingException
     */
    private Task buildTask(OrderMessageEntity orderMessageEntity) throws JsonProcessingException {
        Task taskEntity = new Task();
        String serviceDetail = JsonUtil.objectToJson(orderMessageEntity.getServiceDetail());
        CopyUtils.copyProperties(orderMessageEntity, taskEntity);
        taskEntity.setTaskStatus(TaskOrderAction.TASK_ORDER_WAITING.getAction());
        taskEntity.setVersion(CommonUtil.getUUID());
        taskEntity.setSalary(orderMessageEntity.getPayment());
        taskEntity.setServiceDetail(serviceDetail);
        taskEntity.setDeleteFlag(DeletedFlagEnum.SERVICE_FLAGE_UNDELETED.getCode());
        taskEntity.setAppointmentTime(orderMessageEntity.getAppointment());
        return taskEntity;
    }
}